package vip.liux.front.infrastructure.jdbc.chat;

import org.springframework.data.jdbc.repository.query.Query;
import vip.liux.front.domain.models.chat.ChatConversation;
import vip.liux.front.domain.models.chat.ConversationPair;
import vip.liux.front.domain.models.chat.ConversationWithTargetUser;
import vip.liux.front.domain.models.chat.IChatConversationRepository;

import java.util.List;
import java.util.Objects;

import static vip.liux.core.utils.CollectionUtils.getSingleForList;

public interface ChatConversationJdbcRepository extends IChatConversationRepository {
    @Override
    default ConversationPair findPair(Long senderId, Long targetId) {

        List<ChatConversation> conversations = findById(senderId, targetId);

        if (conversations.isEmpty()) {
            return null;
        }
        return new ConversationPair(
                getSingleForList(conversations.stream().filter(c -> Objects.equals(c.getUserId(), senderId)).toList()),
                getSingleForList(conversations.stream().filter(c -> Objects.equals(c.getUserId(), targetId)).toList())
        );
    }

    @Query("select * from chat_conversations where (user_id = :senderId and target_user_id = :targetId)  or (user_id = :targetId and target_user_id = :senderId)")
    List<ChatConversation> findById(Long senderId, Long targetId);

    @Query("select chatConversation.*, targetUser.* " +
            "from chat_conversations chatConversation " +
            "         left join chat_users targetUser on chatConversation.target_user_id = targetUser.id " +
            "where chatConversation.user_id = :userId " +
            "  and (targetUser.name like concat('%', :filter, '%') or targetUser.surname like concat('%', :filter, '%')) " +
            "order by chatConversation.last_message_date desc")
    @Override
    List<ConversationWithTargetUser> getListByUserId(Long userId, String filter);

    @Query("select sum(unread_message_count) from chat_conversations where user_id = :userId and last_message_side = 1")
    @Override
    int getTotalUnreadMessageCount(Long userId);
}
